package com.example.demo.controller;

import com.example.demo.domain.BlogPost;
import com.example.demo.domain.Comment;
import com.example.demo.service.BlogService;
import com.example.demo.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/")
@Controller
public class BlogController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private BlogService blogService;
    @GetMapping
    public String listPosts(Model model){
        List<BlogPost> posts = blogService.getAllBlogPosts();
        model.addAttribute("posts", posts);
        return "index";
    }

    @GetMapping("/post/create")
    public String showCreatePostForm(Model model){
        model.addAttribute("post", new BlogPost());
        return "create_post";
    }

    @PostMapping("/post/save")
    public String savePost(BlogPost post){
        System.out.println(post);
        blogService.saveBlogPost(post);
        return "redirect:/";
    }

    // Method to show a single blog post and its comments
    @GetMapping("/post/{id}")
    public String viewPost(@PathVariable Long id, Model model) {
        BlogPost post = blogService.getBlogPostById(id);
        List<Comment> comments = commentService.getCommentsByPostId(id);
        model.addAttribute("post", post);
        model.addAttribute("comments", comments);
        model.addAttribute("newComment", new Comment()); // Add this to provide an empty Comment object for the form
        return "post_detail";
    }

    // Method to handle the submission of the comment form
    @PostMapping("/post/{postId}/comments")
    public String addComment(@PathVariable Long postId, @ModelAttribute Comment newComment) {
        newComment.setPostId(postId);
        commentService.addComment(newComment);
        return "redirect:/post/" + postId; // Redirect back to the post detail page
    }

    // Method to handle comment deletion
    @GetMapping("/post/{postId}/comments/{commentId}/delete")
    public String deleteComment(@PathVariable Long postId, @PathVariable Long commentId) {
        commentService.deleteComment(commentId);
        return "redirect:/post/" + postId; // Redirect back to the post detail page
    }
}
